<template>
  <el-card>
    <!-- 表单 -->
    <el-form :model="skuInfo" ref="ruleFormRef" :rules="rules" style="width: 80%" label-width="100px">
      <el-form-item label="SPU名称">{{spuInfo.spuName}}</el-form-item>
      <!-- 名称 -->
      <el-form-item prop="skuName" label="SKU名称">
        <el-input v-model="skuInfo.skuName" placeholder="请输入SKU名称" />
      </el-form-item>
      <!-- 价格 -->
      <el-form-item prop="price" label="价格(元)">
        <el-input v-model="skuInfo.price" type="number" placeholder="0" />
      </el-form-item>
      <!-- 重量 -->
      <el-form-item prop="weight" label="重量(千克)">
        <el-input v-model="skuInfo.weight" type="number" placeholder="0" />
      </el-form-item>
      <!-- 规格描述 -->
      <el-form-item prop="skuDesc" label="规格描述">
        <el-input v-model="skuInfo.skuDesc" type="textarea" rows="4" placeholder="请输入SKU规格描述" />
      </el-form-item>
      <!-- 平台属性 -->
      <el-form-item prop="skuAttrValueList" label="平台属性">
        <el-form inline>
          <el-form-item v-for="(attr, index) in attrInfoList" :key="attr.id" :label="attr.attrName" style="margin-bottom: 10px">
            <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择" @change="clearMsg1">
              <el-option v-for="a2 in attr.attrValueList" :key="a2.id" :label="a2.valueName" :value="a2.id + '-' + attr.id"/>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item prop="skuSaleAttrValueList" label="销售属性">
        <el-form inline>
          <el-form-item v-for="(s1, index) in spuSaleAttrList" :key="s1.id" :label="s1.saleAttrName" style="margin-bottom: 10px">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" placeholder="请选择" @change="clearMsg2">
              <el-option v-for="s2 in s1.spuSaleAttrValueList" :key="s2.id" :label="s2.saleAttrValueName" :value="s2.id" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <!-- 图片 -->
      <el-form-item prop="skuImageList" label="图片列表">
        <!-- 表格 -->
        <el-table :data="spuImgList" ref="imgTableRef" stripe border style="width: 100%" @selection-change="selectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="图片">
            <template v-slot="{row}">
              <img :src="row.imgUrl" :alt="row.imgName" style="widtj: 100px; height: 100px;">
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作" align="center">
            <template v-slot={row}>
              <el-tag v-if="row.isDefault === '1'" type="success">默认</el-tag>
              <el-button v-else type="primary" @click="setDefaultImg(row)">设为默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="saveSku()">保存</el-button>
        <el-button @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script lang="ts">
export default {
  name: 'SkuForm'
}
</script>
<script lang="ts" setup>
import {nextTick, onBeforeUnmount, onMounted, reactive, ref} from 'vue'
// 引入图标组件
import { Delete, Edit, InfoFilled, Plus } from '@element-plus/icons-vue'
// 引入消息提示组件
import {ElMessage, ElMessageBox, ElTable} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 引入Spu组件显示状态标识
import {SpuStatus} from '../SpuStatus'
// 引入Pubsub
import PubSub from 'pubsub-js'

// 引入SPU相关的接口函数及接口类型
import {getSpuImageListByIdApi, getSpuSaleAttrListByIdApi} from '@/api/product/spu'
import type {SpuModel, SpuSaleAttrListModel, SpuImageListModel, SpuImageModel} from '@/api/product/model/spuModel'
// 引入SKU相关的接口函数及接口类型
import {saveOrUpdateSkuInfoApi, saveSkuInfoApi} from '@/api/product/sku'
import type {SkuInfoModel} from '@/api/product/model/skuModel'
// 引入平台属性相关的接口函数及接口类型
import {getAttrInfoListApi} from '@/api/product/attr'
import type {AttrInfoListModel} from '@/api/product/model/attrModel'

// 引入分类仓库
import {useCategoryStore} from '@/stores/category'
const categoryStore = useCategoryStore()

// 定义SPU对象
const spuInfo = reactive<SpuModel>({
  id: undefined,
  spuName: '',
  description: '',
  spuSaleAttrList: [], // 销售属性对象数组
  spuImageList: [] // spu图片对象的数组
}) 
// 定义SKU对象
const skuInfo = ref<SkuInfoModel>({
  id: undefined,
  spuId: spuInfo.id,
  price: undefined,
  skuName: '',
  skuDesc: '',
  weight: '',
  tmId: -1,
  category3Id: categoryStore._category3Id,
  skuDefaultImg: '',
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  isSale: 1
})

const attrInfoList = ref<AttrInfoListModel>([]) // 定义存储平台属性对象数组
const spuSaleAttrList = ref<SpuSaleAttrListModel>([]) // 定义存储销售属性数组
const spuImgList = ref<SpuImageListModel>([]) // 定义存储图片列表数据
// 获取平台属性对象数组
const getAttrInfoList = async () => {
  attrInfoList.value = await getAttrInfoListApi({ 
      category1Id: categoryStore._category1Id, 
      category2Id: categoryStore._category2Id, 
      category3Id: categoryStore._category3Id 
    })
}
// 获取销售属性数组
const getSpuSaleAttrList =async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListByIdApi(spuInfo.id as number)
}

// 获取表格实例
const imgTableRef = ref<InstanceType<typeof ElTable>>()
// 获取图片列表数据
const getSpuImgList =async () => {
  spuImgList.value = await getSpuImageListByIdApi(spuInfo.id as number)
  // 第一张图片设为默认图片
  spuImgList.value.forEach((item, index) => {
    item.isDefault = '0'
  })
  spuImgList.value[0].isDefault = '1'
  // 默认勾选第一张图片
  nextTick(() => {
    imgTableRef.value?.toggleRowSelection(spuImgList.value[0], true)
  })
  // 更新sku
  // skuInfo.value.skuImageList = spuImgList.value
  // 更新默认图片地址
  skuInfo.value.skuDefaultImg = spuImgList.value[0].imgUrl
}
// 切换默认选中的图片
const setDefaultImg = (row: SpuImageModel) => {
  spuImgList.value.forEach(item => {
    // imgTableRef.value?.toggleRowSelection(item, false)
    item.isDefault = '0'
  })
  imgTableRef.value?.toggleRowSelection(row, true)
  row.isDefault = '1'
  // 更新默认图片地址
  skuInfo.value.skuDefaultImg = row.imgUrl
}
// 复选框的值发生变化时
const selectionChange = (selection: SpuImageListModel) => {
  skuInfo.value.skuImageList = selection
}

// 接收父组件传递的方法
const emits = defineEmits(['changeIsShow'])

// 获取表单实例
const ruleFormRef = ref<FormInstance>()
// 表单校验规则
const rules = reactive<FormRules>({
  skuName: [{ required: true, message: 'SKU名称不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '价格是必须的', trigger: 'blur' }],
  weight: [{ required: true, message: '重量是必须的', trigger: 'blur' }],
  skuDesc: [{ required: true, message: 'SKU描述不能为空', trigger: 'blur' }],
  skuAttrValueList: [{ required: true, message: '平台属性至少选择一项', trigger: 'change' }],
  skuSaleAttrValueList: [{ required: true, message: '销售属性至少选择一项', trigger: 'change' }],
  skuImageList: [{ required: true, message: '图片至少选择一张', trigger: 'change' }]
})
// 清理校验信息
const clearMsg1 = (val: string) => {
  if (skuInfo.value.skuAttrValueList.length === 1) {
    ruleFormRef.value?.clearValidate('skuAttrValueList')
  }
}
const clearMsg2 = (val: string) => {
  if (skuInfo.value.skuSaleAttrValueList.length === 1) {
    ruleFormRef.value?.clearValidate('skuSaleAttrValueList')
  }
}
// 保存
const saveSku = () => {
  // 表单验证
  ruleFormRef.value?.validate(async (valid) => {
    // 规则校验未通过
    if (!valid) return
    // 准备参数 调用接口
    try {
      await saveSkuInfoApi({
        ...skuInfo.value,
        spuId: spuInfo.id,
        skuImageList: skuInfo.value.skuImageList.map(item => {
          return {
            imgName: item.imgName,
            imgUrl: item.imgUrl,
            isDefault: item.isDefault,
            spuImgId: item.id
          }
        }).filter(item => item),
        skuAttrValueList: skuInfo.value.skuAttrValueList.map(item => {
          const [id, attrId] = (item as any).split('-') // 解构出来的类型为string需转number
          return {
            // 注意解构顺序 别整错了
            valueId: +id,
            attrId: +attrId
          }
        }),
        skuSaleAttrValueList: skuInfo.value.skuSaleAttrValueList.map(item => ({saleAttrValueId: +item}))
      })
      ElMessage.success('保存成功')
    } catch (error: any) {
      ElMessage.warning(error.message)
    }
    // 跳转回列表页面
    emits('changeIsShow', SpuStatus.Spu_List)
  })  
}
// 取消
const cancel = () => {
  emits('changeIsShow', SpuStatus.Spu_List)
}
// 组件挂载完成
onMounted(() => {
  getAttrInfoList()
  // 订阅
  PubSub.subscribe('getSpuId', (name, val) => {
    Object.assign(spuInfo, val)
    getSpuSaleAttrList()
    getSpuImgList()
  })
})
onBeforeUnmount(() => {
  PubSub.unsubscribe('getSpuId')
})
</script>
<style scoped>
</style>